import Taro from '@tarojs/taro'
import { getBaseUrl,HTTP_STATUS } from './config.js'
import { logError } from '../utils/logError.js'

const token = '123456'

// 延迟加载类
var loading = {
  loadingInstance:null,
  timer:0,//网络延迟时 才显示加载中
  open:function(){
      if(this.timer){
          return ;
      }
      this.timer = setTimeout(()=>{
          this._load();
      },500)
  },
  close:function(){
      if(this.timer){
          clearTimeout(this.timer)
          this.timer = false;
      }
      if(this.loadingInstance!==null){
        Taro.hideLoading();
      }
      this.loadingInstance = null
  },
  _load:function(){
    if(this.loadingInstance==null){
        this.loadingInstance = Taro.showLoading({
          title: '加载中',
        });
        console.log(this.loadingInstance,'----this.loadingInstance')
    }
},
}




export default {
  baseOptions(params, method = 'GET') {
    loading.open();
    let { url, data } = params
    // let token = getApp().globalData.token
    // if (!token) login()
    console.log('params', params)
    let contentType = 'application/x-www-form-urlencoded'
    contentType = params.contentType || contentType
    const option = {
      isShowLoading: false,
      loadingText: '正在加载',
      url: getBaseUrl(url),
      data: data,
      method: method,
      header: { 'content-type': contentType, 'token': token },
      success(res) {
        loading.close();//关闭加载
        if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
          return logError('api', '请求资源不存在')
        } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
          return logError('api', '服务端出现了问题')
        } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
          return logError('api', '没有权限访问')
        } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
          return res.data
        }
      },
      error(e) {
        logError('api', '请求接口出现问题', e)
      }
    }
    return Taro.request(option)
  },
  get(url, data = '') {
    let option = { url, data }
    return this.baseOptions(option)
  },
  post: function (url, data, contentType) {
    let params = { url, data, contentType }
    return this.baseOptions(params, 'POST')
  }
}